package com.szy.redstonemcu;

import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

import javax.swing.*;


public class McuBaseBlock extends Block {
    public McuBaseBlock(){
        super(Material.ROCK);
        setHardness(0.5f);

    }

    @Override
    public boolean hasTileEntity(IBlockState state) {
        return true;
    }



    @Override
    public TileEntity createTileEntity(World p_createTileEntity_1_, IBlockState p_createTileEntity_2_) {

        return new McuBaseEntity();
    }

//    @Override
//    public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float p_180639_7_, float p_180639_8_, float p_180639_9_) {
//        TileEntity tile = world.getTileEntity(pos);
//        RedstoneMCU.logger.info("right click");
//        if (!world.isRemote && tile instanceof RM8FAA_Entity) {
//
//            int c=((RM8FAA_Entity) tile).get_time();
//            player.sendStatusMessage(new TextComponentString("time: " + c), true);
//            RedstoneMCU.logger.info("right click on mcu,time="+c);
//            //player.openGui(RedstoneMCU.instance, 1, world, pos.getX(), pos.getY(), pos.getZ());
//            return true;
//        }
//        return false;
//    }


    //RM8FAA_Entity entity=new RM8FAA_Entity();



    //redstone out
    @Override
    public boolean canProvidePower(IBlockState iBlockState)
    {
        return true;
    }

    /** How much weak power does this block provide to the adjacent block?
     * See http://greyminecraftcoder.blogspot.com.au/2015/11/redstone.html for more information
     * @param worldIn
     * @param pos the position of this block
     * @param state the blockstate of this block
     * @param side the side of the block - eg EAST means that this is to the EAST of the adjacent block.
     * @return The power provided [0 - 15]
     */

    @Override
    public int getWeakPower(IBlockState state, IBlockAccess worldIn, BlockPos pos,  EnumFacing side)
    {
//        if(! (side == EnumFacing.EAST)){
//            return 0;
//        }q
        //Integer powerIndex = (Integer)state.getValue(POWER_INDEX);
        TileEntity tile = worldIn.getTileEntity(pos);
        int power=0;
        if(side == EnumFacing.EAST){
            power=((McuBaseEntity)tile).getIoPower(3);
        }else if(side == EnumFacing.SOUTH){
            power=((McuBaseEntity)tile).getIoPower(2);
        }else if(side == EnumFacing.WEST){
            power=((McuBaseEntity)tile).getIoPower(1);
        }else if(side == EnumFacing.NORTH){
            power=((McuBaseEntity)tile).getIoPower(0);
        }

        if (power < 0) {
            power = 0;
        } else if (power > 15) {
            power = 15;
        }
        return power;
    }

    // The variable source block does not provide strong power.  See BlockButton for a example of a block which does.
    @Override
    public int getStrongPower(IBlockState state, IBlockAccess worldIn, BlockPos pos, EnumFacing side)
    {
        return 0;
    }

    //--------- methods associated with storing the currently-selected power

    // one property for this block - the power level it is providing, index = 0 - 4 which maps to [0, 4, 8, 12, 15]

//    private static final int POWER_VALUES [] = {0, 4, 8, 12, 15};
//    private static final int MAXIMUM_POWER_INDEX = POWER_VALUES.length - 1;
//    public static final PropertyInteger POWER_INDEX = PropertyInteger.create("power_index", 0, MAXIMUM_POWER_INDEX);

    // getStateFromMeta, getMetaFromState are used to interconvert between the block's property values and
    //   the stored metadata (which must be an integer in the range 0 - 15 inclusive)
//    @Override
//    public IBlockState getStateFromMeta(int meta)
//    {
//        return this.getDefaultState().withProperty(POWER_INDEX, Integer.valueOf(meta));
//    }
//
//    @Override
//    public int getMetaFromState(IBlockState state)
//    {
//        return (Integer)state.getValue(POWER_INDEX);
//    }



    // this method isn't required if your properties only depend on the stored metadata.
    // it is required if:
    // 1) you are making a multiblock which stores information in other blocks eg BlockBed, BlockDoor
    // 2) your block's state depends on other neighbours (eg BlockFence)
//    @Override
//    public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
//    {
//        return state;
//    }
//
//    // necessary to define which properties your blocks use
//    // will also affect the variants listed in the blockstates model file
//    @Override
//    protected BlockStateContainer createBlockState()
//    {
//        return new BlockStateContainer(this, new IProperty[] {POWER_INDEX});
//    }


    // Every time the player right-clicks, cycle through to the next power setting.
    // Need to trigger an update and notify all neighbours to make sure the new power setting takes effect.
    @Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand,
                                    EnumFacing side, float hitX, float hitY, float hitZ)
    {

        if (!playerIn.capabilities.allowEdit) {
            return false;
        } else {
            if(worldIn.isRemote){
//                ItemStack stack=playerIn.getHeldItem(hand);
//                if(stack.getItem() instanceof Flash){
//                    NBTTagCompound tag= stack.getTagCompound();
//                    tag.setString("code",);
//                }else{
                if(playerIn.getHeldItem(EnumHand.MAIN_HAND).getItem() != RedstoneMCU.flashItem && playerIn.getHeldItem(EnumHand.OFF_HAND).getItem() != RedstoneMCU.flashItem){
                    RedstoneMCU.simpleNetworkWrapper.sendToServer(new McuMessage(pos, McuMessage.TYPE_REQUEST_GUI));
                }

//                }

                //playerIn.openGui(RedstoneMCU.instance, 1, worldIn, pos.getX(), pos.getY(), pos.getZ());
                //Minecraft.getMinecraft().displayGuiScreen(new EditScreen());
//                ItemStack stack=playerIn.getHeldItem(hand);
//                Item item=stack.getItem();
//                if(item == Items.WRITABLE_BOOK){
//                    RedstoneMCU.logger.info("book");
//                    NBTTagCompound nbttagcompound=stack.getTagCompound();
//                    NBTTagList bookPages = nbttagcompound.getTagList("pages", 8).copy();
//                    int bookTotalPages = bookPages.tagCount();
//                    RedstoneMCU.logger.info("page : "+bookTotalPages);
//                    RedstoneMCU.logger.info("context: "+bookPages);
//                }
                //playerIn.openBook(new ItemStack(this),hand);
                //entity=(RM8FAA_Entity) worldIn.getTileEntity(pos);
//                final int MARK_BLOCKS_FOR_UPDATE_FLAG = 2;
//                final int NOTIFY_NEIGHBOURS_FLAG = 1;
//                worldIn.setBlockState(pos, state.cycleProperty(POWER_INDEX),
//                        MARK_BLOCKS_FOR_UPDATE_FLAG | NOTIFY_NEIGHBOURS_FLAG);
//                worldIn.setBlockState(pos,state,
//                        MARK_BLOCKS_FOR_UPDATE_FLAG | NOTIFY_NEIGHBOURS_FLAG);
                //worldIn.notifyNeighborsOfStateChange(pos, this, false);
            }else{
//                TileEntity entity=worldIn.getTileEntity(pos);
//                if(entity instanceof RM8FAA_Entity){
//                    RM8FAA_Entity te=(RM8FAA_Entity) entity;
//                    RedstoneMCU.simpleNetworkWrapper.sendTo(new MCUMessage(pos,MCUMessage.TYPE_READ_CODE,te.codeText),(EntityPlayerMP) playerIn);
//                    if(te.simulator.runningState()){
//                        RedstoneMCU.simpleNetworkWrapper.sendTo(new MCUMessage(pos,MCUMessage.TYPE_RETURN_ASSEMBLE_RESULT,"Running"),(EntityPlayerMP) playerIn);
//                    }else{
//                        RedstoneMCU.simpleNetworkWrapper.sendTo(new MCUMessage(pos,MCUMessage.TYPE_RETURN_ASSEMBLE_RESULT,"Pause at\n"+te.simulator.getCurrentInstruction().getOriginalText()),(EntityPlayerMP) playerIn);
//                    }
//
//
//                }
                ItemStack mainHeldItem = playerIn.getHeldItem(EnumHand.MAIN_HAND);
                ItemStack offHeldItem = playerIn.getHeldItem(EnumHand.OFF_HAND);
                if(mainHeldItem.getItem() == RedstoneMCU.flashItem){
                    McuBaseEntity entity=(McuBaseEntity)worldIn.getTileEntity(pos);
                    String code=mainHeldItem.getTagCompound().getString("code");
                    if(code.length() > 0){
                        assert entity != null;
                        entity.codeText=code;
                    }
                    RedstoneMCU.logger.info("load code to mcu");
                    TextComponentTranslation translation=new TextComponentTranslation("message.redstonemcu.load_to_mcu");
                    playerIn.sendStatusMessage(translation, false);


                }
                if(offHeldItem.getItem() == RedstoneMCU.flashItem){
                    NBTTagCompound tag=new NBTTagCompound();
                    McuBaseEntity entity=(McuBaseEntity)worldIn.getTileEntity(pos);
                    assert entity != null;
                    tag.setString("code",entity.codeText);
                    offHeldItem.setTagCompound(tag);

                    RedstoneMCU.logger.info("store code to flash");
                    TextComponentTranslation translation=new TextComponentTranslation("message.redstonemcu.store_to_flash");
                    playerIn.sendStatusMessage(translation, false);
                    if(!offHeldItem.getDisplayName().endsWith("*")){
                        offHeldItem.setStackDisplayName(offHeldItem.getDisplayName()+"*");
                    }
                }
            }


            return true;
        }
    }




    @Override
    public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) {
        super.neighborChanged(state, worldIn, pos, blockIn, fromPos);
        if(!worldIn.isRemote){
            TileEntity entity=worldIn.getTileEntity(pos);
            if(entity instanceof McuBaseEntity){
                McuBaseEntity te=(McuBaseEntity) entity;
                if(pos.offset(EnumFacing.EAST).equals(fromPos)){
                    te.ioChangedByHardware(1,worldIn.getRedstonePower(fromPos,EnumFacing.EAST));
                } else if (pos.offset(EnumFacing.SOUTH).equals(fromPos)) {
                    te.ioChangedByHardware(0,worldIn.getRedstonePower(fromPos,EnumFacing.SOUTH));
                }else if (pos.offset(EnumFacing.WEST).equals(fromPos)) {
                    te.ioChangedByHardware(3,worldIn.getRedstonePower(fromPos,EnumFacing.WEST));
                }else if (pos.offset(EnumFacing.NORTH).equals(fromPos)) {
                    te.ioChangedByHardware(2,worldIn.getRedstonePower(fromPos,EnumFacing.NORTH));
                }


            }
        }
    }

    // When the block is broken, you may need to notify neighbours.
    @Override
    public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
    {
        final boolean CASCADE_UPDATE = false;  // I'm not sure what this flag does, but vanilla always sets it to false
        // except for calls by World.setBlockState()
        McuBaseEntity te=(McuBaseEntity) worldIn.getTileEntity(pos);
        ItemStack stack=new ItemStack(RedstoneMCU.mcuBase);

        NBTTagCompound tag=new NBTTagCompound();
        tag.setString("code",te.codeText);
        stack.setTagCompound(tag);

        //RedstoneMCU.logger.info("break, code="+te.codeText);
        EntityItem item=new EntityItem(worldIn,pos.getX()+0.5,pos.getY()+0.5,pos.getZ()+0.5,stack);
        worldIn.spawnEntity(item);
        worldIn.notifyNeighborsOfStateChange(pos, this, CASCADE_UPDATE);
        super.breakBlock(worldIn, pos, state);
    }

    @Override
    public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
        //super.getDrops(drops, world, pos, state, fortune);
    }

    @Override
    public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {

        super.onBlockPlacedBy(worldIn, pos, state, placer, stack);
        McuBaseEntity te=(McuBaseEntity) worldIn.getTileEntity(pos);
        NBTTagCompound tag=stack.getTagCompound();
        RedstoneMCU.logger.info("place block");
        if(tag != null){
            te.codeText=tag.getString("code");
        }

    }
//    private int c2;
//    @Override
//    public void update() {
//        if(++c2>20){
//            c2=0;
//            RedstoneMCU.logger.info("block tick");
//        }
//
//    }
}
